//
//  ZYStatusOriginalView.swift
//  CZ29WeiboZYH
//
//  Created by 沐颜澈 on 16/6/27.
//  Copyright © 2016年 muyanche. All rights reserved.
//

import UIKit

//记录约束重新导入
import SnapKit

//边距
private let OriginalMargin: CGFloat = 10

class ZYStatusOriginalView: UIView {
    
    //630====声明一个全局的原创微博的底部的约束提供卸载
    var originalViewBottomConstraint: Constraint?
    
    
    //给外界设置数据
    var status: ZYStatusModel? {
        didSet {
            //给名字赋值
            nickNameLabel.text = status?.user?.name
            //给用户图像赋值
            headImgeView.sd_setImageWithURL(NSURL(string: status?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            
            //处理时间和日期    ---------------------630  541
            //时间
            //timeLabel.text = "伦敦时间" 7.1改动
            timeLabel.text = status?.createAtStr
            
            //来源
            sourceLabel.attributedText = status?.sourceAttr
            
            //print(status?.source)
            
            //处理微博的内容
            contentLabel.attributedText = status?.textAttr
            
            //7.7
//            getWeiboAttr(status?.text ?? "")
            
            
            //认证的图片
//            vipImgView.image = getVipImage(status?.user?.verified_type ?? -1)
            vipImgView.image = status?.user?.verifiedImage
            
            //会员的等级
            
//            expiredImageView.image = getMbrankImage(status?.user?.mbrank ?? 0)
            expiredImageView.image = status?.user?.mbrankImage
            
            /*
            （考虑到cell的复用问题）
            01 先卸载原创微博的底部约束
            02 如果status?.pic_urls.count > 0 代表有配图
            - 显示配图
            - 要先赋值 然后进行约束
            - 原创微博的底部 == 配图的底部 + 10（更新约束）
            反之 <= 0  均是没有配图
            - 隐藏配图
            - 原创微博的底部 == 微博正文的底部 + 10（更新约束）
            */
            originalViewBottomConstraint?.uninstall()
            if status?.pic_urls?.count > 0 {
                pictureView.hidden = false
                //赋值
                pictureView.pic_urls = status?.pic_urls
                
                //更新约束
                self.snp_makeConstraints { (make) -> Void in
                    originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(StatusMargin).constraint    //630  记录约束
                    
                }
            
            } else {
                
                pictureView.hidden = true
                self.snp_makeConstraints { (make) -> Void in
                    originalViewBottomConstraint = make.bottom.equalTo(contentLabel).offset(StatusMargin).constraint    //630  记录约束
                    
                }
                
            }
           
        }
        
    }
    
    
    //--------------7.7--------------
    
        
    
//删掉了时间的处理
    
    /*
    Optional("<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>")
    Optional("<a href=\"http://app.weibo.com/t/feed/3auC5p\" rel=\"nofollow\">皮皮时光机</a>")
    Optional("<a href=\"http://app.weibo.com/t/feed/3auC5p\" rel=\"nofollow\">皮皮时光机</a>")
    */
    
    //630===微博来源的字符串处理
    func getSourceStr(source:String?) -> NSMutableAttributedString {
        
        guard let s = source where s.containsString("\">") else {
            let  r = "来自火星的你"

            
            return getSourceAttr(r)
        
        }
        
        //字符串的获取
        let start = s.rangeOfString("\">")!
        let end = s.rangeOfString("</a")!
        //字符串的获取
        let result = s.substringWithRange(start.endIndex..<end.startIndex)
        //完成字符串的拼接
        let r = "来自\(result)"

        return getSourceAttr(r)
    
    }
    
    //通过字符串来生成一个富文本
    func getSourceAttr(result: String) -> NSMutableAttributedString{
        // 实例化一个富文本
        let attr = NSMutableAttributedString(string: result)
        // 获取range
        let range = (result as NSString).rangeOfString("来自")
        // 设置属性
        attr.addAttributes([NSForegroundColorAttributeName: ThemeColor], range: range)
        return attr
    }
    
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置视图
    private func setupUI() {
    
        backgroundColor = UIColor.whiteColor()
        //添加到控件
        addSubview(headImgeView)
        addSubview(nickNameLabel)
        addSubview(expiredImageView)
        addSubview(sourceLabel)
        addSubview(vipImgView)
        addSubview(timeLabel)
        addSubview(contentLabel)    //629
        //630.添加约束
        addSubview(pictureView)
        
        
        //图像的添加约束
        headImgeView.snp_makeConstraints { (make) -> Void in
            make.leading.top.equalTo(self).offset(OriginalMargin)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        //昵称的约束
        nickNameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImgeView)
            make.leading.equalTo(headImgeView.snp_trailing).offset(OriginalMargin)
            
        }
        
        //用户等级的约束
        expiredImageView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nickNameLabel.snp_trailing).offset(OriginalMargin)
            make.centerY.equalTo(nickNameLabel)
            
        }
        
        //发布的时间
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nickNameLabel.snp_leading).offset(2)
            make.bottom.equalTo(headImgeView)
        }
        
        //来自于
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(timeLabel)
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
            
        }
        
        //VIP图标
        vipImgView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(headImgeView.snp_trailing)
            make.centerY.equalTo(headImgeView.snp_bottom)
        }
        
        //设置微博内容的约束 629
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(headImgeView)
            make.top.equalTo(headImgeView.snp_bottom).offset(StatusMargin)
        }
        
        //630 原创微博配图的约束==================================
        pictureView.snp_makeConstraints { (make) -> Void in
            //make.size.equalTo(CGSize(width: 100, height: 100))
            make.leading.equalTo(contentLabel)
            make.top.equalTo(contentLabel.snp_bottom).offset(StatusMargin)
        }
        
        
        //629,原创微博的的约束,取决于文字的高度
        self.snp_makeConstraints { (make) -> Void in
           originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(StatusMargin).constraint    //630  记录约束
            
        }
        
        
        //contentLabel.text = "最近，苹果将默认编译器从GCC转换为LLVM(low level virtual machine)，从此不再需要为属性声明实例变量了。如果LLVM发现一个没有匹配实例变量的属性，它将自动创建一个以下划线开头的实例变量。因此，在这个版本中，我们不再为输出口声明实例变量。"

    }
    
    
    ////MARK: - 懒加载控件
    //图像
    private lazy var headImgeView: UIImageView = UIImageView(imagName: "avatar_default_big")
    
    //用户的昵称
    private lazy var nickNameLabel: UILabel = {
        let nickNameLabel = UILabel()
        nickNameLabel.textColor = UIColor.grayColor()
        nickNameLabel.text = "李白"
        nickNameLabel.font = UIFont.systemFontOfSize(12)
        
        return nickNameLabel
    }()
    
    //用户的等级
    private lazy var expiredImageView: UIImageView = UIImageView(imagName: "common_icon_membership_expired")
    
    //发布微博事件
    private lazy var timeLabel: UILabel = {
        let timeLabel = UILabel()
        timeLabel.font = UIFont.systemFontOfSize(12)
        timeLabel.text = "一分前"
        timeLabel.textColor = RandomColor()
        return timeLabel
        
    }()

    //微博的来源
    private lazy var sourceLabel: UILabel = {
        
        let label = UILabel()
        label.textColor = RandomColor()
        label.text = "来自星星"
        label.font = UIFont.systemFontOfSize(12)
        return label
    
    }()
    
    //VIP图标
    private lazy var vipImgView: UIImageView = UIImageView(imagName: "avatar_vgirl")
    
    //=================629微博的内容
    private lazy var contentLabel: UILabel = UILabel(textColor: UIColor.blackColor(), textFont: 15, maxWidth: SCREENW - 2*StatusMargin)
    
    //630----原创微博的配图
    private lazy var pictureView: ZYPictureView = ZYPictureView()
    
}


//
extension ZYStatusOriginalView {

    func getMbrankImage(mbRank: Int) -> UIImage? {
        
        //print("会员等级")
        if mbRank > 0 && mbRank < 7{
            
            return UIImage(named: "common_icon_membership_level\(mbRank)")
        } else {
            
            return UIImage(named: "common_icon_membership_expired")
        }
        
    }
    
    //定义一个方法,认证图片
    // 通过后台返回来的数据来判断/// 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    func getVipImage(verified: Int) -> UIImage? {
        
       // print("认证类型")
        switch verified {
        case 0:
            return UIImage(named: "avatar_vip")
        case 2, 3, 5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
            
        }
        
    }


}





